﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Runtime.Serialization;
using QbservableCore.Serialization.Helpers;

namespace QbservableCore.Serialization
{
    [DataContract]
    public class ParameterNode : ExpRepresentationBase
    {
        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public LightweightSerializableType TypeToken { get; set; }

        protected internal override Expression ToExpression(ExepressionBuilderCache exepressionBuilderCache)
        {
            ParameterExpression parameter;
            if (!exepressionBuilderCache.ParameterExpressionCache.TryGetValue(this, out parameter))
            {
                Type type = TypeToken.ToType();
                parameter = Expression.Parameter(type, Name);
                exepressionBuilderCache.ParameterExpressionCache.Add(this, parameter);
            }

            return parameter;
        }

        public override int GetHashCode()
        {
            return Name.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            return obj is ParameterNode && 
                ((ParameterNode)obj).Name == this.Name &&
                TypeToken._fullyQualifiedTypeName == ((ParameterNode)obj).TypeToken._fullyQualifiedTypeName;
        }

        protected override void TraverseChildren(Func<ExpRepresentationBase, ExpRepresentationBase> action) { }

        public override string ToString()
        {
            return Name;
        }
    }
}